package org.angelica.modules.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.angelica.modules.account.dao.AccRoleDao;
import org.angelica.modules.account.entity.AccRoleDO;
import org.angelica.modules.account.entity.AccRolePermDO;
import org.angelica.modules.account.form.AccRoleCreateForm;
import org.angelica.modules.account.form.AccRoleUpdateForm;
import org.angelica.modules.account.service.AccRolePermService;
import org.angelica.modules.account.service.AccRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author aizhimin
 * @since 2019-05-13
 */
@Service
public class AccRoleServiceImpl extends ServiceImpl<AccRoleDao, AccRoleDO> implements AccRoleService {

    @Autowired
    private AccRolePermService accRolePermService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertRole(AccRoleCreateForm accRoleCreateForm) {
        //保存角色信息
        AccRoleDO accRoleDO = AccRoleDO.builder().build();
        BeanUtils.copyProperties(accRoleCreateForm,accRoleDO);
        accRoleDO.setGmtCreate(Calendar.getInstance().getTime());
        this.save(accRoleDO);
        //保存角色与权限关系数据
        accRolePermService.saveRolePerms(accRoleDO.getId(),accRoleCreateForm.getPerms());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(AccRoleUpdateForm accRoleUpdateForm) {
        //更新角色信息
        AccRoleDO accRoleDO = AccRoleDO.builder().build();
        BeanUtils.copyProperties(accRoleUpdateForm,accRoleDO);
        accRoleDO.setGmtModified(Calendar.getInstance().getTime());
        this.updateById(accRoleDO);
        //保存角色与权限关系数据
        accRolePermService.saveRolePerms(accRoleDO.getId(),accRoleUpdateForm.getPerms());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Long roleId) {
        //删除角色信息
        this.removeById(roleId);
        //删除角色与权限关系信息
        accRolePermService.remove(new QueryWrapper<AccRolePermDO>().eq("role_id",roleId));
    }
}
